import { logout, userinfo } from '@/api/homeApi'
import { Loading } from 'element-ui'
import { setToken, getToken } from '@/utils/auth'
const state = {
  userInfo: JSON.parse(sessionStorage.getItem('userInfo')) || ''
}

const mutations = {
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
    sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
  }
}

const actions = {
  getUserInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {
      userinfo().then(res => {
        const { data } = res
        if (data) {
          commit('SET_USERINFO', data)
          resolve(data)
        } else {
          resolve({})
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  loginout ({ commit, state }) {
    const loadingInstance = Loading.service({
      lock: true,
      text: '退出登录中，请稍候...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    logout().then(res => {
       loadingInstance.close()
       setToken('')
       commit('SET_USERINFO', '')
            //跳转到登录, 如果当前在首页就不调整，不在首页跳转首页
          if (window.location.pathname !== '/index') {
              window.location.replace('/index')
          }
        // window.location.replace('/login')
        
     }).catch(() => {
       loadingInstance.close()
     })
    // setTimeout(() => {
    //   sessionStorage.clear()
    //   loadingInstance.close()
    //   window.location.href = process.env.VUE_APP_SSO_URL + '/sso/logout'
    // }, 600)
  },
  setTheme ({ commit }, state) {
    commit('SET_THEME', state)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
